package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import com.oocl.dao.UserDao;
import com.oocl.pojo.User;
import com.oocl.util.DBUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public int addUser(User c) {
		String sql = "insert into userList(id, name, pwd) values (?,?,?)";
		
		PreparedStatement pst =null;
		Connection con = null;
		int m = 0; 
		
		try {
			con = DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, c.getId());
			pst.setString(2, c.getName());
			pst.setString(3, c.getPwd());
			
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, null);
		}
		return m;
	}

	@Override
	public User checkUser(String name, String pwd) {
		String sql = "select * from userList where name=? and pwd=?";
		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection con = DBUtil.createConnection();
		User c = null;
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			pst.setString(2, pwd);
			rs = pst.executeQuery();
			
			if(rs.next()){
				c = new User();
				c.setId(rs.getString("id"));
				c.setName(rs.getString("name"));
				c.setPwd(rs.getString("pwd"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, rs);
		}
		return c;
	}

	@Override
	public void initUser() {
		for(int i = 0; i < 5; i++){
			User c = new User(UUID.randomUUID().toString(),"jordan_" + i, "123");
			addUser(c);
		}
	}
	
	public static void main(String[] args) {
		UserDaoImpl impl = new UserDaoImpl();
		impl.initUser();
	}
}
